package com.txy.domain.strategy.service.raffle;

import com.txy.domain.strategy.model.entity.StrategyAwardEntity;
import com.txy.domain.strategy.service.IRaffleService;
import com.txy.domain.strategy.model.entity.RaffleAwardEntity;
import com.txy.domain.strategy.model.entity.RaffleFactorEntity;
import com.txy.domain.strategy.repository.IStrategyRepository;
import com.txy.domain.strategy.service.armory.IStrategyDispatch;
import com.txy.domain.strategy.service.rule.chain.factory.LogicChainFactory;
import com.txy.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.apache.commons.lang3.StringUtils;

public abstract class AbstractRaffleService implements IRaffleService {
    protected IStrategyDispatch strategyDispatch;

    protected IStrategyRepository repository;

    protected LogicChainFactory logicFactory;

    protected DefaultTreeFactory defaultTreeFactory;

    AbstractRaffleService(IStrategyDispatch strategyDispatch, IStrategyRepository repository, LogicChainFactory logicFactory, DefaultTreeFactory defaultTreeFactory) {
        this.strategyDispatch = strategyDispatch;
        this.repository = repository;
        this.logicFactory = logicFactory;
        this.defaultTreeFactory = defaultTreeFactory;
    }

    public RaffleAwardEntity performRaffle(RaffleFactorEntity raffleFactorEntity) {
        // 参数校验
        if (raffleFactorEntity == null) return null;

        Long strategyId = raffleFactorEntity.getStrategyId();
        String userId = raffleFactorEntity.getUserId();
        if (strategyId == null || StringUtils.isBlank(userId)) {
            return null;
        }

        // 责任链 抽奖
        LogicChainFactory.LogicChainRes logicChainRes = logicChain(strategyId, userId);
        if (!logicChainRes.getLogicModel().equals(LogicChainFactory.LogicModel.DEFAULT)) {
            return buildRaffleAwardEntity(strategyId, logicChainRes.getAwardId(), null);
        }

        // 规则树 抽奖规则过滤
        DefaultTreeFactory.AwardResClass resClass = logicTree(strategyId, userId, logicChainRes.getAwardId());

        return buildRaffleAwardEntity(strategyId, resClass.getAwardId(), null);
    }

    private RaffleAwardEntity buildRaffleAwardEntity(Long strategyId, Integer awardId, String awardConfig) {
        StrategyAwardEntity strategyAward = repository.queryStrategyAwardEntity(strategyId, awardId);
        return RaffleAwardEntity.builder()
                .awardId(awardId)
                .awardConfig(awardConfig)
                .sort(strategyAward.getSort())
                .build();
    }

    protected abstract LogicChainFactory.LogicChainRes logicChain(Long strategyId, String userId);

    protected abstract DefaultTreeFactory.AwardResClass logicTree(Long strategyId, String userId, Integer awardId);
}
